package taskclient

import (
	"cm2/service"
	"cm2/service/log"
	"cm2/service/task"
	"cm2/terminal/worker/win-web/global"
	"fmt"

	"github.com/go-xorm/xorm"
)

// RunTaskService 启动任务服务
func RunTaskService() {
	log.DefaultLogger().Info("launching task tcp client service")
	global.TaskServShutdown = make(chan bool, 1)

	tsConfig := service.DefaultConfig["taskServer"].(map[string]interface{})
	tsAddr := tsConfig["addr"].(string)
	tsPort := int(tsConfig["port"].(float64))
	tsAddress := fmt.Sprintf("%s:%d", tsAddr, tsPort)

	ttc := task.NewClient(
		service.SId,
		fmt.Sprintf("task tcp client service (%s @ %s)", service.SName, service.SId),
		service.SType,
		tsAddress,
	)
	ttc.SetLogger(log.NamedLogger("default"))

	tsRetryConfig := service.DefaultConfig["readRetry"].(map[string]interface{})
	tsRetryTimes := int(tsRetryConfig["times"].(float64))
	tsRetryDuration := int(tsRetryConfig["duration"].(float64))
	ttc.SetReadRetryParams(tsRetryTimes, tsRetryDuration)

	tsDialConfig := service.DefaultConfig["dialRetry"].(map[string]interface{})
	tsDialRetryDuration := int(tsDialConfig["duration"].(float64))
	ttc.SetDialRetryParams(tsDialRetryDuration)
	ttc.SetOnJobReceived(service.DefaultJobService().BeginExecuteJob)
	ttc.SetLogFn(
		service.DefaultJobService().CreateJobLog,
		service.DefaultJobService().UpdateJobTaskLogState,
	)

	// 注册为默认的task client
	service.RegisterTaskClient("default", ttc)

	go func() {
		ttc.Start()
		global.TaskServShutdown <- true
	}()
}

// RunJobService 启动 job service
func RunJobService(jbp *xorm.Engine) {
	js := task.NewJobService(service.SId, service.SName)
	js.SetLogger(log.NamedLogger("default"))
	js.SetConcurrency(int(service.DefaultConfig["concurrency"].(float64)))
	js.SetMaxProc(int(service.DefaultConfig["maxproc"].(float64)))
	js.SetJobLogProvider(jbp)

	// 注册为默认的job service
	service.RegisterJobService("default", js)

	js.Start()
}
